<?php
define('E_NONE', '');
class Helper
{
	/**
	* Subsite first N word in the text as an intro text
	* 
	* @param mixed $originalString
	* @param mixed $wordsCount
	* @return string
	*/
	public static function getDisplayedWords($originalString, $wordsCount)
	{
		$displayedText = $originalString;
		$totalWords = explode(' ', $originalString);
		$temp = array();
		if (count($totalWords) > $wordsCount)
		{
			for ($i = 0; $i < $wordsCount; $i++)
			{
				$temp[] = $totalWords[$i];
			}
			$displayedText = implode(' ', $temp) . '...';
		}
		return $displayedText;
	}
	
	    /**
    * Create a Dom XML document from HTML string
    * 
    * @param mixed $html
    * @param mixed $ver
    * @param mixed $encoding
    * @return DOMDocument
    */
    public static function createXMLDocFromHTML($html, $ver = '1.0', $encoding = 'utf-8')
    {
        $tmp = self::htmlEntitiesToChars($html);
        if ($tmp != null) 
            $html = $tmp;
        
        $doc = new DOMDocument();
        libxml_use_internal_errors(true);
        $doc->loadHTML($html);
        return $doc;
    }
    
    public static function htmlEntitiesToChars($str)
    {
        //Convert HTML decimal/hexa entities to characters
//        if (mb_detect_encoding($str) == 'UTF-8'){
//            decode decimal HTML entities added by web browser
            $str = preg_replace('/&#\d{2,5};/ue', "self::utf8_entity_decode('$0')", $str);
//            decode hex HTML entities added by web browser
            $str = preg_replace('/&#x([a-fA-F0-7]{2,8});/ue', "self::utf8_entity_decode('&#'.hexdec('$1').';')", $str );            
//            decode named characters
            $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
//            echo $str.'<br />';
//        }
        return $str;    
    }

    //callback function for the regex
    public static function utf8_entity_decode($entity){    
        $convmap = array(0x0, 0x10000, 0, 0xfffff); 
        return mb_decode_numericentity($entity, $convmap, 'UTF-8');
    }

      
    /**
    * Open an URL using CURL
    * 
    * @param string $url Url to open
    * @param string $referer referer url
    * @param string $postfields data to post, in querystring format
    * @param string $method post method, possible value: post, get
    * @param bool $useSSL whether to use SSL or not
    * @param bool $header prepend HTTP header into response
    * @param array $httpheader HTTP header to post with the request
    * @param string $cookieFile path to cookie file to save and load cookies, must be r/writable
    * 
    * @return string
    */
    public function curlRequest($url, $referer = '', $postfields = '', $method = 'get', $useSSL = false, $header = false, $httpheader = array(), $cookieFile = '')
    {
        //Set agent
        $agent = @$_SERVER['HTTP_USER_AGENT'];
        if(empty($agent))
            $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
            
        if ($method=='get' && $postfields != '')
            $url .= '?'.$postfields;

        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL, $url); 
        curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
        
        if ($postfields != '')
            curl_setopt($ch, CURLOPT_POST, true);
        else
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            
        if ($method == 'post');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
        
        if ($method == 'get')
            curl_setopt($ch, CURLOPT_HTTPGET, true);
        
        if ($header)
            curl_setopt($ch, CURLOPT_HEADER, 1); 
        
        $httpheader[] = "ContentType: application/xml; charset=utf-8";
        $httpheader[] = "Cache-Control: max-age=0";
        $httpheader[] = "Connection: keep-alive";
        $httpheader[] = "Keep-Alive: 300";
        $httpheader[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $httpheader[] = "Pragma: ";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
            
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
        
        //The contents of the "Referer: " header to be used in a HTTP request.
        if ($referer != '')
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        
        if (!empty($cookieFile))
        {
            $cookie_file_path = realpath($cookieFile);
            // The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. 
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
            // The name of a file to save all internal cookies to when the connection closes. 
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 
            
            if ($method == 'post')
            {
                $file = fopen($cookie_file_path, 'w');
                fwrite($file, '');
                fclose($file);
            }
        }
        
        if ($useSSL)
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
        }
        
        $result = curl_exec($ch); // grab URL and pass it to the variable.
        curl_close($ch); // close curl resource, and free up system resources.
        
        return $result;
    }
    

    /**
    * Save a string to file
    * 
    * @param mixed $str
    * @param mixed $filename
    */
    public static function stringToFile($str, $filename){
        $f = fopen($filename, 'w');
        fwrite($f, $str);
        fclose($f);
    }        
    
    public static function toAscii($from, $to, $str)
    {
        mb_internal_encoding("UTF-8");        
        for ($i=0; $i<mb_strlen($from); $i++)
        {
            $fromChar = mb_substr($from, $i,1);
            $toChar = mb_substr($to, $i,1);
            $str = mb_eregi_replace("\\".$fromChar, $toChar, $str);
        }
        //return $str;
        return mb_convert_encoding($str,'ASCII');
    }
    
    public static function removeAccent($str)
    {        
        $uni_from = ' ()!$?:,&+=><ÀàÁáÂâẢảÃãÄäÅåĀāĂăĄąǞǟǺǻÆæǼǽẠạẬậẶặẤấẮắẦầẪẫẨẩẲẳẴẵẰằḂḃĆćÇçČčĈĉĊċḐḑĎďḊḋĐđðǄǆÈèÉéĚěÊêỂểËëĒēĔĕĘęĖėƷʒǮǯẸẹỆệẺẻỄễẾếỀềẼẽḞḟǴǵĢģǦǧĜĝĞğĠġĤĥĦħÌìÍíÎîĨĩÏïĪīĬĭĮįİıỊịỈỉĴĵḰḱĶķǨǩĹĺĻļĽľĿŀŁłṀṁŃńŅņŇňÑñŉŊŋǊǌÒòÓóƠơỜờÔôÕõÖöŌōŎŏØøŐőǾǿŒœỌọỢợỘộỒồỞởỎỏỚớỐốỔổỖỗỠỡṖṗŔŕŖŗŘřɼŚśŞşŠšŜŝṠṡſßŢţŤťṪṫŦŧÞþÙùÚúÛûỦủŨũÜŮůŪūŬŭŲųŰűỤụỰựÙừỨứƯưỬửỮữẀẁẂẃŴŵẄẅỲỳÝýŶŷŸÿỴỵỸỹỶỷŹźŽžŻż`~';    
        $uni_to = '-____________AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaBbCcCcCcCcCcDdDdDdDddDdEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeFfGgGgGgGgGgGgHhHhIiIiIiIiIiIiIiIiIiIiIiJjKkKkKkLlLlLlLlLlMmNnNnNnNnnNnNnOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoPpRrRrRrrSsSsSsSsSsSsTtTtTtTtTtUuUuUuUuUuUUuUuUuUuUuUuUuUuUuUuUuUuWwWwWwWwYyYyYyYyYyYyYyZzZzZz__';
        $from = "\\'\"/.@#%^*".$uni_from;
        $to   = '__________'.$uni_to;
       
        return strtolower(self::toAscii($from, $to, $str));
    }

    public static function utf8Trim($text){
        iconv_set_encoding("internal_encoding", "UTF-8");
        $text = iconv("UTF-8", "ASCII//IGNORE", $text);
        return trim($text);
    }
    
    public static function generateAlias($str){

        $strReturn = $str;

        $utfChar=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
        "ằ","ắ","ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề"
        ,"ế","ệ","ể","ễ",
        "ì","í","ị","ỉ","ĩ",
        "ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
        ,"ờ","ớ","ợ","ở","ỡ",
        "ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
        "ỳ","ý","ỵ","ỷ","ỹ",
        "đ",
        "À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
        ,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
        "È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
        "Ì","Í","Ị","Ỉ","Ĩ",
        "Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
        ,"Ờ","Ớ","Ợ","Ở","Ỡ",
        "Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
        "Ỳ","Ý","Ỵ","Ỷ","Ỹ",
        "Đ",
        " ",",","?",";",":","/",".","'",'"',"(",")","&","%","#","_",'$',"!","@","^","*","+","=","|",'\\','{','}','[',']','<','>','`',"~",'“','”','’'
        );

        $nonUtfChar=array("a","a","a","a","a","a","a","a","a","a","a"
        ,"a","a","a","a","a","a",
        "e","e","e","e","e","e","e","e","e","e","e",
        "i","i","i","i","i",
        "o","o","o","o","o","o","o","o","o","o","o","o"
        ,"o","o","o","o","o",
        "u","u","u","u","u","u","u","u","u","u","u",
        "y","y","y","y","y",
        "d",
        "A","A","A","A","A","A","A","A","A","A","A","A"
        ,"A","A","A","A","A",
        "E","E","E","E","E","E","E","E","E","E","E",
        "I","I","I","I","I",
        "O","O","O","O","O","O","O","O","O","O","O","O"
        ,"O","O","O","O","O",
        "U","U","U","U","U","U","U","U","U","U","U",
        "Y","Y","Y","Y","Y",
        "D",
        "-","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
        );

        $strReturn = str_replace($utfChar,$nonUtfChar,$strReturn);
        $strReturn = strtolower($strReturn);

        return str_replace("?","",$strReturn);
    }
}
?>
